/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Personas;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author nan
 */
public class personaListar implements ActionListener, KeyListener{

    private Conexion.ConexionBD conectar = new Conexion.ConexionBD();
    private personaListarGUI ventana = new personaListarGUI();
    private Personas.MedAltaPer persona;
    private Personas.MedModPer Mpersona ;
    private DefaultTableModel dtmPersona;

    public personaListar(){
        ventana.setLocationRelativeTo(null);
        ventana.setActionListeners(this);
        ventana.setKeyListener(this);
        ventana.setVisible(true);
        actualizarTabla();
    }

    public void actualizarTabla(){
        String[] titulos = {"DNI", "Nombre", "Apellido", "Direccion", "Telefono", "Nombre Usuario", "Contraseña", "Tipo Usuario"};
        Object[][] datos = {};
        dtmPersona = new DefaultTableModel(datos, titulos);

        conectar.conectar();
        Statement st;
        try {
            st = conectar.getConn().createStatement();
            String consulta = "SELECT * FROM \"Personas\"";
            ResultSet rs = st.executeQuery(consulta);
            String id = null;
            while (rs.next()){
                Object[] fila = {rs.getString(1),
                rs.getString(2),
                rs.getString(3),
                rs.getString(4),
                rs.getString(5),
                rs.getString(6),
                rs.getString(7),
                rs.getString(8)};
                dtmPersona.addRow(fila);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        ventana.getjTableArticulos().setModel(dtmPersona);
    }

    public void actualizarPorCampo(String nombre,String DNI){
        String[] titulos = {"DNI", "Nombre", "Apellido", "Direccion", "Telefono", "Nombre Usuario", "Contraseña", "Tipo Usuario"};
        Object[][] datos = {};
        dtmPersona = new DefaultTableModel(datos, titulos);

        conectar.conectar();
        Statement st;
        try {
            st = conectar.getConn().createStatement();
            String consulta = "SELECT * FROM \"Personas\" WHERE \"TipoUser\"='"+nombre+"' OR \"DNI\" = '"+DNI+"';" ;
            ResultSet rs = st.executeQuery(consulta);
            String id = null;
            while (rs.next()){
                Object[] fila = {rs.getString("DNI"),
                rs.getString("Nombre"),
                rs.getString("Apellido"),
                rs.getString("Direccion"),
                rs.getString("Telefono"),
                rs.getString("NomUsuario"),
                rs.getString("Contrasenia"),
                rs.getString("TipoUser")};
                dtmPersona.addRow(fila);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        ventana.getjTableArticulos().setModel(dtmPersona);
        conectar.cerrar();
    }

    public void actionPerformed(ActionEvent e) {
        int select = ventana.getjTableArticulos().getSelectedRow();
        if (e.getSource() == ventana.getjButtonAgregar()){
            if (this.persona == null){
                persona = new Personas.MedAltaPer(this);
            } else {
                persona.setVisible(true);
            }
        } else if (e.getSource() == ventana.getjButtonMostrarTodos()){
            actualizarTabla();
            ventana.getjTextFieldCod().setText("");
            ventana.getjTextFieldNombre().setText("");
        } else if (e.getSource() == ventana.getjButtonEliminar()){
            eliminar(select);
        } else if (e.getSource() == ventana.getjButtonModificar()){
            if (select != -1){
                if (this.Mpersona == null){
                    Mpersona = new MedModPer(this);
                    Mpersona.setClave(dtmPersona.getValueAt(select, 0).toString());
                    Mpersona.getIngreso().getjTextFieldNombre().setText(dtmPersona.getValueAt(select, 1).toString());
                    Mpersona.getIngreso().getjTextFieldApellido().setText(dtmPersona.getValueAt(select, 2).toString());
                    Mpersona.getIngreso().getjTextFieldDireccion().setText(dtmPersona.getValueAt(select, 3).toString());
                    Mpersona.getIngreso().getjTextFieldTelefono().setText(dtmPersona.getValueAt(select, 4).toString());
                    Mpersona.getIngreso().getjTextFieldNombreUser().setText(dtmPersona.getValueAt(select, 5).toString());
                    Mpersona.getIngreso().getjTextFieldContra().setText(dtmPersona.getValueAt(select, 6).toString());
                    Mpersona.getIngreso().getTipoUser().setText(dtmPersona.getValueAt(select, 7).toString());
                } else {
                    Mpersona.setClave(dtmPersona.getValueAt(select, 0).toString());
                    Mpersona.getIngreso().getjTextFieldNombre().setText(dtmPersona.getValueAt(select, 1).toString());
                    Mpersona.getIngreso().getjTextFieldApellido().setText(dtmPersona.getValueAt(select, 2).toString());
                    Mpersona.getIngreso().getjTextFieldDireccion().setText(dtmPersona.getValueAt(select, 3).toString());
                    Mpersona.getIngreso().getjTextFieldTelefono().setText(dtmPersona.getValueAt(select, 4).toString());
                    Mpersona.getIngreso().getjTextFieldNombreUser().setText(dtmPersona.getValueAt(select, 5).toString());
                    Mpersona.getIngreso().getjTextFieldContra().setText(dtmPersona.getValueAt(select, 6).toString());
                    Mpersona.getIngreso().getTipoUser().setText(dtmPersona.getValueAt(select, 7).toString());
                    Mpersona.setVisible(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Debe seleccionar un elemento", "Error por seleccion nula", JOptionPane.ERROR_MESSAGE);
        }
        } if (e.getSource() == ventana.getjButtonMostrarCampo()){
            String cod = ventana.getjTextFieldCod().getText();
            String nombre =ventana.getjTextFieldNombre().getText();
            actualizarPorCampo(nombre,cod);
            ventana.getjTextFieldCod().setText("");
            ventana.getjTextFieldNombre().setText("");
        }
        if (e.getSource() == ventana.getjButtonSalir()){
            ventana.dispose();
        }
    }

    private void eliminar(int select){
        if (select != -1){
            String a = dtmPersona.getValueAt(select, 0).toString();

            conectar.conectar();
            int confirmado = JOptionPane.showConfirmDialog(null,"¿Está seguro que desea eliminar el articulo?", "Eliminar Articulo", JOptionPane.YES_NO_OPTION);

            if (JOptionPane.OK_OPTION == confirmado){
                try {
                    Statement st = conectar.getConn().createStatement();
                    System.out.println(a);
                    String borrar = "DELETE FROM \"Personas\" WHERE \"DNI\" = '"+a+"';";
                    System.out.println(st.execute(borrar));
                    st.close();
                } catch (Exception ex) {   
                    ex.printStackTrace();
                }
                conectar.cerrar();
                this.actualizarTabla();
                JOptionPane.showMessageDialog(null, "Se ha eliminado el Articulo", "Elemento eliminado", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Debe seleccionar un elemento", "Error por seleccion nula", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void keyTyped(KeyEvent e) {

    }

    public void keyPressed(KeyEvent e) {   }

    public void keyReleased(KeyEvent e) {   }

    public void setVisible(boolean b) {
        ventana.setVisible(b);
    }

}
